package com.idol.logger.core.printer.window

import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.graphics.Point
import android.os.Bundle
import android.view.WindowManager
import com.idol.logger.core.printer.data.LoggerMo
import com.idol.logger.core.printer.iface.IdolPrinter
import com.idol.logger.core.printer.window.service.IdolWindowService
import com.idol.logger.utils.asNull

class IdolWindowPrinter private constructor(private val application: Application) : IdolPrinter {

    companion object {
        private val lock: Any = Any()
        internal var windowHeight = 0; private set
        private var isRunning: Boolean = false
        private var instance: IdolWindowPrinter? = null

        private fun screen(application: Application) = Point().also { point ->
            (application.getSystemService(Context.WINDOW_SERVICE) as? WindowManager)?.run {
                defaultDisplay.getSize(point)
            }
        }

        /**
         * start windows printer.
         * @param application   Application
         * @param height        the panel`s height, length unit: px
         */
        fun setUp(application: Application, height: Int = 0) = instance ?: synchronized(lock) {
            instance ?: IdolWindowPrinter(application).also {
                instance = it
                windowHeight = asNull(height, height <= 0) ?: (screen(application).y / 2)
            }
        }

        /**
         * start service, and add mode to recycleView.
         */
        private fun startServiceAndInsertModel(mo: LoggerMo) = instance?.apply {
            Intent(application, IdolWindowService::class.java).also {
                it.putExtra(IdolWindowService.KEY, mo)
                registerCallbacks()
                isRunning = true
                application.startService(it)
            }
        }

        /**
         * stop service.
         */
        fun stop() = instance?.apply {
            if (isRunning) {
                isRunning = false
                unregisterCallbacks()
                application.stopService(Intent(application, IdolWindowService::class.java))
            }
        }
    }

    private var isRegister = false

    private var size: Int = 0 // activity size.
        set(value) {
            field = value
            if (value == 0) stop()
        }

    private val callback = object : Application.ActivityLifecycleCallbacks {
        override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
            size++
        }

        override fun onActivityDestroyed(activity: Activity) {
            size--
        }

        override fun onActivityResumed(activity: Activity) {
            val intent = Intent(application, IdolWindowService::class.java)
            intent.putExtra(IdolWindowService.DISPLAY, true)
            application.startService(intent)
        }

        override fun onActivityPaused(activity: Activity) {
            val intent = Intent(application, IdolWindowService::class.java)
            intent.putExtra(IdolWindowService.DISPLAY, false)
            application.startService(intent)
        }

        override fun onActivityStarted(activity: Activity) = Unit
        override fun onActivityStopped(activity: Activity) = Unit
        override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
    }
    
    // 此处init不能放在上面，会出现空指针问题
    init {
        registerCallbacks()
    }

    private fun registerCallbacks() {
        if (isRegister) return
        isRegister = true
        application.registerActivityLifecycleCallbacks(callback)
    }

    private fun unregisterCallbacks() {
        if (!isRegister) return
        isRegister = false
        application.unregisterActivityLifecycleCallbacks(callback)
    }

    override fun print(level: Int, tag: String, printString: String) {
        startServiceAndInsertModel(LoggerMo(System.currentTimeMillis(), level, tag, printString))
    }

}